import axios from 'axios'
import { useMain,store } from "../store/index";
import { getUserRefreshToken, isDialog,deleteCookie } from "../utils/utils"
import router from "../routes/index"
import { useRouter } from 'vue-router';



axios.defaults.timeout = 15000;
if(import.meta.env.VITE_ENV!='production'){
axios.defaults.baseURL = import.meta.env.VITE_BASE_API
}else{
    axios.defaults.baseURL = location.origin;
}
// axios.defaults.withCredentials = true; //设置cross跨域 并设置访问权限 允许跨域携带cookie信息
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// axios.defaults.headers['Content-Type'] = 'Content-Type:application/json; charset=UTF-8'; //配置axios的基础请求头
axios.defaults.headers['Content-Type'] = 'application/json; charset=UTF-8';

let loading: any = null;

const useMainStore = useMain(store);
//请求拦截器
axios.interceptors.request.use((config) => {

    const token = useMainStore.authToken ? useMainStore.authToken : '';
    const currentProjectInfo: any = useMainStore.currentProjectInfo ? useMainStore.currentProjectInfo : {};

    const showSpread: any = useMainStore.showSpread;
    if (token) {
        // 在发起请求前，给所有请求的头部添加token
        config.headers['Authorization'] = token;
    }
    //当请求刷新令牌接口时,请求头添加refreshToken
    if (config.url == '/user/auth/refreshToken' && useMainStore.refreshToken) {
        config.headers['Refresh-Token'] = useMainStore.refreshToken;
    }
    if (currentProjectInfo && currentProjectInfo.projectId) {
        // 在发起请求前，给所有请求的头部添加token
        config.headers['Project-Id'] = currentProjectInfo.projectId;
    }
    //平台类型
    config.headers['Platform-Type'] = 3;
    

    //验证图形验证码时,设置Content-Type
    if (config.url == '/user/captcha/verifyPicCaptcha') {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    let loading_options = {
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0)',
        customClass: showSpread ? 'loading_showSpread' : 'loading_showSpread_not'
    }
    let currentPath = router.currentRoute.value.path;
    //登录等页面不添加类名
    if (currentPath == '/realTime/viewEquipment' || currentPath == '/equipmentOperations/equipmentOperationsDetails' || currentPath == '/equipmentOperations/equipmentOperationsAdd' || currentPath == '/equipmentOperations/equipmentOperationsPoint' || currentPath == '/login' || currentPath == '/alarmCenter/addRule' || currentPath == '/forgetPassword'|| currentPath == '/basicInfo/assetListAdd'|| currentPath == '/basicInfo/spaceChangeRecord'|| currentPath == '/basicInfo/asset'|| currentPath == '/basicInfo/stationChangeRecord') {
        loading_options.customClass = ""
    }

    //如果是在弹窗中的请求,不添加类名
    if (isDialog(config.url)) {
        loading_options.customClass = ""
    }

    if (config.method == 'get' && !config.params.noLoading) {
        loading = ElLoading.service(loading_options)
    } else if (config.method == 'post' && !config.data.noLoading) {
        loading = ElLoading.service(loading_options)
    }

    return config
}, (error) => {
    return Promise.reject(error)
})



//响应拦截器
axios.interceptors.response.use(response => {
    loading && loading.close();//关闭loading
    loading = null;//清空loading


    let res = response.data;
    if (!response.data) {
        res = response;
    }

    if (res && res.resultCode === '200' || res.resultCode === '201') {//请求成功时的处理
        return Promise.resolve(res);
    } else if (res && (res.resultCode === '403' || res.resultCode === '403-2' || res.resultCode === '403-3' || res.resultCode === '403-4' || res.resultCode === '403-5' || res.resultCode === '403-6')) {
        // window.location.href = "/login";
        //清空登录信息
        useMainStore.updatedAuthToken("");
        useMainStore.updatedRefreshToken("");
        useMainStore.updatedUserInfo({});
        deleteCookie("authToken");
        deleteCookie("refreshToken");
        router.push('/login');
    }
    else {//请求失败时的处理
        
        //不用统一报错方式的特殊处理
        if (response.config && ((response.config.url == '/msg/shortMsg/sendSmsCode' && res.resultMsg && res.resultMsg == '手机号未登记')|| (response.config.url == '/device/useTypeFloor/add' && res.resultMsg && res.resultMsg.indexOf('请修改后再重试')>-1) || (response.config.url == '/device/useTypeRoom/add' && res.resultMsg && res.resultMsg.indexOf('已存在，请修改后再重试')>-1) ||(response.config.url == '/device/useTypeRoom/del' && res.resultMsg && res.resultMsg.indexOf('删除空间内存在企业绑定')>-1))) {

        } else {
            ElMessage({
                message: res.resultMsg ? res.resultMsg : "连接超时,请稍后重试",
                grouping: true,
                type: 'error',
            })
        }
    }
    return Promise.reject(res)
}, async (error) => {
    
    loading && loading.close();//关闭loading
    loading = null;//清空loading
    if (error.response && error.response.data) {
        if (error.response.data.resultCode == '403-1') {
            await getUserRefreshToken();
            return axios(error.config)
        } else if (error.response.data.resultCode == '403' || error.response.data.resultCode == '403-2' || error.response.data.resultCode == '403-3' || error.response.data.resultCode == '403-4' || error.response.data.resultCode == '403-5' || error.response.data.resultCode == '403-6') {
            //清空登录信息
            useMainStore.updatedAuthToken("");
            useMainStore.updatedRefreshToken("");
            useMainStore.updatedUserInfo({});
            deleteCookie("authToken");
            deleteCookie("refreshToken");
            router.push('/login');
        } else {
            ElMessage({
                message: error.response.data.resultMsg ? error.response.data.resultMsg : "连接超时,请稍后重试",
                grouping: true,
                type: 'error',
            })
        }
    } else if (error.resultCode && error.resultMsg) {
        if (error.resultCode == '403-1') {
            await getUserRefreshToken();
            return axios(error.config)
        } else if (error.resultCode == '403' || error.resultCode == '403-2' || error.resultCode == '403-3' || error.resultCode == '403-4' || error.resultCode == '405' || error.resultCode == '406') {
            //清空登录信息
            useMainStore.updatedAuthToken("");
            useMainStore.updatedRefreshToken("");
            useMainStore.updatedUserInfo({});
            deleteCookie("authToken");
            deleteCookie("refreshToken");
            router.push('/login');
        } else {
            ElMessage({
                message: error.resultMsg ? error.resultMsg : "连接超时,请稍后重试",
                grouping: true,
                type: 'error',
            })
        }
    } else {
        ElMessage({
            message: "连接超时,请稍后重试",
            grouping: true,
            type: 'error',
        })
    }
    return Promise.reject(error)
})
export default axios

/**
* 封装get方法
* @param url
* @param params
* @returns {Promise}
*/

export function get(url: any, params: Object = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
            .then(response => {
                resolve(response)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/

export function post(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
    })
}

/**
* 封装delete方法
* @param url
* @param params
* @returns {Promise}
*/

export function doDelete(url: any, params: Object = {}) {
    return new Promise((resolve, reject) => {
        axios.delete(url, {
            params: params
        })
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/

export function patch(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/

export function put(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}